package com.cxmx.escort.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxmx.escort.base.BaseController;
import com.cxmx.escort.base.ResponseFormat;
import com.cxmx.escort.base.Result;
import com.cxmx.escort.baseEnum.VariableEnum;
import com.cxmx.escort.common.SnowflakeIdWorker;
import com.cxmx.escort.common.redis.RedisUtils;
import com.cxmx.escort.entity.*;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.time.LocalTime;

/**
 * <p>
 * 充值表 前端控制器
 * </p>
 *
 * @author 陈云轩
 * @since 2019-10-21
 */
@RestController
@RequestMapping("/bed")
@Validated
@Api(value = "床", tags = {"陪护床操作接口"})
@SuppressWarnings("unchecked")
public class BedController extends BaseController {
    @ApiOperation(value = "扫码开锁", httpMethod = "POST")
    @PostMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
    })
    public Result<Boolean> addFeedBack(String code, @NotNull(message = "token不可为空") @RequestHeader("token") String token) {
        if (null == code || code.length() != 15) {
            return ResponseFormat.retParam(70017, null);
        }
        QueryWrapper<BedOrder> qw = new QueryWrapper<BedOrder>();
        qw.ne("order_status", 3);
        qw.eq("user_id", getLongTypeUserId(token));
        int a = bedOrderService.count(qw);
        if (a > 0) {
            return ResponseFormat.retParam(70010, null);
        }
        QueryWrapper<BedOrder> qwr = new QueryWrapper<BedOrder>();
        qwr.eq("order_status", 1);
        qwr.eq("bed_code", code);
        int b = bedOrderService.count(qwr);
        if (b > 0) {
            return ResponseFormat.retParam(70011, null);
        }

        //查询是否可开锁
        QueryWrapper<Bed> qwb = new QueryWrapper<>();
        qwb.eq("bed_code", code);
        Bed bed = bedService.getOne(qwb);
        if (null != bed) {
            if (null == bed.getHospitalId()) {
                return ResponseFormat.retParam(70015, null);
            } else {
                Region region = regionService.getById(bed.getHospitalId());
                if (region.getDisableFlag() == 2
                        && LocalTime.now().isAfter(region.getBeginTime())
                        && LocalTime.now().isBefore(region.getEndTime())) {
                    return ResponseFormat.retParam(70016, null);
                }
            }
        } else {
            return ResponseFormat.retParam(70015, true);
        }

        Object key = RedisUtils.get("bed:getUserId:" + getStringTypeUserId(token));
        if (null != key) {
            return ResponseFormat.retParam(70014, null);
        }

        //缓存锁编号
        RedisUtils.set("bed:setUserId:" + getStringTypeUserId(token), code, 60);

        return ResponseFormat.retParam(200, true);
    }


    @ApiOperation(value = "开锁先支付抵扣金", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
    })
    @PostMapping("pay")
    public Result<Boolean> addTop(@NotNull(message = "token不可为空") @RequestHeader("token") String token) throws WxPayException {
        Object key = RedisUtils.get("bed:getUserId:" + getStringTypeUserId(token));
        if (null != key) {
            return ResponseFormat.retParam(70014, null);
        }
        User user = userService.getById(getLongTypeUserId(token));
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();
//        Double price = top.getPrice().doubleValue() * 100;
//        wxPayUnifiedOrderRequest.setTotalFee(Integer.parseInt(String.valueOf(price.intValue())));
        wxPayUnifiedOrderRequest.setTotalFee(VariableEnum.THE_DEPOSIT.getCode());
        wxPayUnifiedOrderRequest.setBody("陪护床抵扣金充值");
        String id = String.valueOf(SnowflakeIdWorker.getId());
        wxPayUnifiedOrderRequest.setOutTradeNo(id);
        wxPayUnifiedOrderRequest.setOpenid(user.getOpenId());
        wxPayUnifiedOrderRequest.setTradeType("JSAPI");
        wxPayUnifiedOrderRequest.setSpbillCreateIp("47.105.133.34");
        wxPayUnifiedOrderRequest.setNotifyUrl("https://api.bochenkj.cn/pay/notify/order");
        wxPayUnifiedOrderRequest.setFeeType("CNY");
        wxPayUnifiedOrderRequest.setVersion("1.0");
        Top top = new Top();
        top.setUserId(String.valueOf(getUserId(token)));

        top.setId(id);
        top.setDeleteFlag(1);
        top.setConsumptionType(1);
        boolean e = topService.save(top);
//        if (e) {
//            user.setBalance(user.getBalance().add(top.getPrice()));
//        }
//        userService.updateById(user);
        return ResponseFormat.retParam(200, wxService.createOrder(wxPayUnifiedOrderRequest));
    }
}

